<?php

	class SluzobneCesty extends CI_Controller {
		
		function __construct() {
			parent::__construct();
			$this->load->helper('form');
			$this->load->library('form_validation');
			
			if( $logged_in = $this->session->userdata('logged_in') ){
				$this->load->model('SluzobneCesty_model');
				$this->load->model('people_model');
				$this->load->model('logs_model');
				//$this->load->view('hlavna_stranka_view');
			} else {
                if ($this->router->fetch_method() !== 'index') {
                    redirect(site_url('SluzobneCesty'));
                } else {
                    $this->load->view('neprihlaseny_view');
                }
			} 

		}
		
		function index(){
                        $this->load->helper('form');
			$logged_in = $this->session->userdata('logged_in');
			if( $logged_in ){
				$this->load->view('hlavna_stranka_view');
			}	
		}
                
                function changePassword() {
                    $this->load->library('form_validation');
                    
                    $this->form_validation->set_rules('pw[old_password]', 'Staré heslo', 'required|callback__testPassword');
                    $this->form_validation->set_rules('pw[new_password]', 'Nové heslo', 'required|min_length[6]|max_length[32]');
                    $this->form_validation->set_rules('pw[new_password_confirm]', 'Potvrdenie nového hesla', 'required|matches[pw[new_password]]');
                    $this->form_validation->set_message('_testPassword', 'Políčko %s musí obsahovať aktuálne heslo k účtu používateľa.');
                    
                    if ($this->form_validation->run()) {
                        $pw = $this->input->post('pw');
                        $user_id = $this->session->userdata('user_id');
                        $new_password = $pw['new_password'];
                        unset($pw);
                        $this->load->model('auth_model');
                        if ($this->auth_model->change_password($user_id, $new_password)) {
                            $this->session->set_flashdata('change_password', 'Heslo bolo úspešne zmenené.');
                        } else {
                            $this->session->set_flashdata('change_password', 'Zmena hesla bola neúspešná.');
                        }
                        redirect('SluzobneCesty');
                    } else {
                        $this->index();
                    }
                }
                
                function _testPassword($old_password) {
                    $user_id = $this->session->userdata('user_id');
                    $this->load->model('auth_model');
                    return $this->auth_model->check_old_password($user_id, $old_password);
                }
		
		function _getPeople($ids){
			$pole_ids = explode(',', $ids);
			$result = array();
			for ($i=0; $i < sizeof($pole_ids); $i++) { 
				$result[$i] = $this->people_model->GetPerson($pole_ids[$i]);		
			}
			return $result;
		}
		
		function getPriCesty(){
			return $this->SluzobneCesty_model->getPriCesty();
		}
		
		function getOdCesty(){
			return $this->SluzobneCesty_model->getOdCesty();
		}
		
		//vrati vsetky cesty		
		function getAll($table = ''){
                        $this->inject_cities($table);
                        $this->inject_countries($table);
                        $this->inject_organizations($table);
                        $this->inject_persons($table);
                        $filter_default = array('page' => 1, 'per_page' => 20);
                        $restored_filter = $this->restore_filter($table);
                        $filter = array_merge($filter_default, is_array($restored_filter) ? $restored_filter : array(), is_array($this->input->post('filter')) ? $this->input->post('filter') : array());
                        $this->store_filter($table, $filter);
			if( $table == 'pricestovani' ){
				$cesty = array(
					'pricesty' => $this->SluzobneCesty_model->getPriCesty($filter),
					//'odcesty' => $this->SluzobneCesty_model->getOdCesty(),
					'unique' => $this->GenerateUnique($table),
                                        'filter' => $filter,
				);
				
				$this->load->view('cesty_view',$cesty);
			}else if( $table == 'odcestovani' ){
				$cesty = array(
					//'pricesty' => $this->SluzobneCesty_model->getPriCesty(),
					'odcesty' => $this->SluzobneCesty_model->getOdCesty($filter),
					'unique' => $this->GenerateUnique($table),
                                        'filter' => $filter,
				);
				$this->load->view('odcesty_view',$cesty);	
			}else {
				//ak get nie je dobry
				$this->load->view('hlavna_stranka_view'); 
			}
		}
		
		//vyselektuje data co su v db a da ich do formulara
		function zmenCestu($table,$id){
			if( $table == 'pricestovani' ) {
				$data['typ_cesty'] = 'pricestovani';
				$data['cesta'] = $this->SluzobneCesty_model->getPriCestaById($id);
			}else if( $table == 'odcestovani' ){
				$data['typ_cesty'] = 'odcestovani';
				$data['cesta'] = $this->SluzobneCesty_model->getOdCestaById($id);
			}
		
			$this->load->view('zmen_cestu_view',$data);
		}
		
		//prida sluzobnu cestu
		function add(){
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
			
			//nastavenie validacie
			$this->form_validation->set_rules('city','<u><i>mesto</i></u>','required|trim|addslashes');
			$this->form_validation->set_rules('country','<u><i>štát</i></u>','required|trim|addslashes');
			$this->form_validation->set_rules('organization','<u><i>organizácia</i></u>','required|trim|addslashes');
			$this->form_validation->set_rules('date_of_arrival','<u><i>dátum príchodu</i></u>','required|trim|addslashes');
			$this->form_validation->set_rules('date_of_departure','<u><i>dátum odchodu</i></u>','required|trim|addslashes');
			//$this->form_validation->set_rules('types[]','typ cesty','required');
			
			if ( $this->form_validation->run() == FALSE ){
				//chyba este raz loadneme form
				$pageData['unique'] = $this->GenerateUnique($this->input->post('types'));
				if( $this->input->post('types') == 'odcestovani' ){
					$pageData['odcesty'] = $this->SluzobneCesty_model->getOdCesty();
					$this->load->view('odcesty_view',$pageData);
				} 
				if( $this->input->post('types') == 'pricestovani' ){
					$pageData['pricesty'] = $this->SluzobneCesty_model->getPriCesty();
					$this->load->view('cesty_view',$pageData);
				}
			} else {
				//validacia ok 
				//data z formulara co vyplnil user
				$data = array(
					'id' => NULL,
					'person_id' => '',
					'city' => $this->input->post('city'),
					'country' => $this->input->post('country'),
					'organization' => $this->input->post('organization'),
					'date_of_arrival' => $this->input->post('date_of_arrival'),
					'date_of_departure' => $this->input->post('date_of_departure'),
					'unique' => $this->input->post('unique')
				);
				$table = $this->input->post('types');
				
				
				$pridane = $this->SluzobneCesty_model->add($table, $data);
				$pageData = array();
				if (!$pridane){
					//cesta nie je pridana loadujem este raz view
					if( $this->input->post('types') == 'pricestovani' ){
						$pageData['error'] = '<div class="error">Cesta nebola pridana</div>';
						$this->load->view('cesty_view',$pageData);	
					}
					if( $this->input->post('types') == 'odcestovani' ){
						$pageData['error'] = '<div class="error">Cesta nebola pridana</div>';
						$this->load->view('odcesty_view',$pageData);					
					}
				} else {
					//vytvorim logs data
					$tmp_cesta = $this->SluzobneCesty_model->getByUnique($table, $this->input->post('unique'));//vyberiem cestu co sa zapisal naposledy 			
					$logsAction = 'pridal cestu:' . $tmp_cesta['id'] . ':' . $data['city'] . ':' . $data['country']; //vytvorim action co urobil user

					$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
					
					//$id_cesty = $this->SluzobneCesty_model->getByUnique($table, $data['unique']);
					redirect('SluzobneCesty/ukaz/'.$table.'/'.$tmp_cesta['id']);
				}
				
			}	
		}
		
		function GenerateUnique($table){
			$ok = TRUE;
			while ($ok) {				
				$random= "";
				srand((double)microtime()*1000000);
				$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
				$char_list .= "abcdefghijklmnopqrstuvwxyz";
				$char_list .= "1234567890";
				// Add the special characters to $char_list if needed
				
				for($i = 0; $i < 10; $i++)  
				{    
				   $random .= substr($char_list,(rand()%(strlen($char_list))), 1);  
				}  
				
				$ok = $this->SluzobneCesty_model->kontrola($table,$random);
			}
			return $random;
		}
		
		//ukaze podrobnosti o sluz. ceste
		function ukaz($from, $id){
			if ( $from == 'odcestovani' ) {
				$pageData['cesta'] = $this->SluzobneCesty_model->getOdCestaById($id);
				$pageData['typ_cesty'] = $from;
				$pageData['id_cesty'] = $id;				
			} else if ( $from == 'pricestovani' ) {
				$pageData['cesta'] = $this->SluzobneCesty_model->getPriCestaById($id);
				$pageData['typ_cesty'] = $from;
				$pageData['id_cesty'] = $id;
			} else {
				redirect('SluzobneCesty/GetAll');	
			}
			//ak je niekto priradeny k ceste tak pridam ich do pageData
			if( !empty($pageData['cesta'][0]['person_id']) ){
				$pageData['priradeni_ludia'] = $this->_getPeople($pageData['cesta'][0]['person_id']);
				$tmp_ids = explode(',', $pageData['cesta'][0]['person_id']);//pole ids ludi ktore su priradeni k ceste, tychto ludi uz nedam do dropboxu
			}
			$ludia = $this->people_model->getAll();//vyberiem vsetkych ludi 
			
			$tmp_ids = explode(',', $pageData['cesta'][0]['person_id']);//pole ids ludi ktore su priradeni k ceste, tychto ludi uz nedam do dropboxu 
			//vytvorim asoc pole pre form drop_down 
			foreach ($ludia as $key => $obj) {
				$meno = $obj['name'] . ' ' . $obj['surname'];
				if( !in_array($obj['person_id'], $tmp_ids) ){ //ak clovek este nie je priradeny k ceste tak ho dame do dropboxu
					$options_drop_box[$obj['person_id']] = $meno;
				}
			}

			$pageData['options_drop_box'] = $options_drop_box;//nastavenie form dropdown
			
			$this->load->view('cesta_podrobnosti_view',$pageData);		
		}
		
		
		//edituje uz existujucu cestu
		function zmen(){
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
			
			//nastavenie validacie
			$this->form_validation->set_rules('city','City','required|trim|addslashes');
			$this->form_validation->set_rules('country','Country','required|trim|addslashes');
			$this->form_validation->set_rules('organization','Organization','required|trim|addslashes');
			$this->form_validation->set_rules('date_of_arrival','date_of_arrival','required|trim|addslashes');
			$this->form_validation->set_rules('date_of_departure','date_of_departure','required|trim|addslashes');
			
				$id = $this->input->post('id');
				if( $this->input->post('typ_cesty') == 'pricestovani' ) {
					$data['typ_cesty'] = 'pricestovani';
					$data['cesta'] = $this->SluzobneCesty_model->getPriCestaById($id);
				}else if( $this->input->post('typ_cesty') == 'odcestovani' ){
					$data['typ_cesty'] = 'odcestovani';
					$data['cesta'] = $this->SluzobneCesty_model->getOdCestaById($id);
				}
			
			
			if( $this->form_validation->run() == FALSE ){
				//chybne vyplneny form
	
	
				$this->load->view('zmen_cestu_view',$data);
			} else {
				//dobre vyplneny formular
				$data = array(
					'id' => $this->input->post('id'),
					'person_id' => $this->input->post('person_id'),
					'city' => $this->input->post('city'),
					'country' => $this->input->post('country'),
					'organization' => $this->input->post('organization'),
					'date_of_arrival' => $this->input->post('date_of_arrival'),
					'date_of_departure' => $this->input->post('date_of_departure')
				);
				$table = $this->input->post('typ_cesty');
				$result = $this->SluzobneCesty_model->zmen($table,$data);
				if( $result ){
					//uspesne zmenene udaje
					//vytvorim logs data 
					$logsAction = 'zmenil cestu:' . $data['id'] . ':' . $data['city'] . ':' . $data['country']; //vytvorim action co urobil user
					$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
					redirect('SluzobneCesty/ukaz/'.$table.'/'.$data['id']);
				} else {
					//chyba
				}
			}
						
		}
		
		//vymaze cestu z db
		function delete($table,$id){
			$deleted = $this->SluzobneCesty_model->delete($table,$id);	
			if ( $deleted ){
				if( $table == 'pricestovani' ) redirect('SluzobneCesty/getAll/pricestovani');
				if( $table == 'odcestovani' ) redirect('SluzobneCesty/getAll/odcestovani');
			} else {
				//chyba				
			}
		}
		
		function odober($typcesty, $idcesty, $personid){
			$pageData = array();
			if ( $typcesty == 'odcestovani' ) {
				$cesta = $this->SluzobneCesty_model->getOdCestaById($idcesty);
				//$cesta['typ_cesty'] = $typcesty;
			} else if ( $typcesty == 'pricestovani' ) {
				$cesta = $this->SluzobneCesty_model->getPriCestaById($idcesty);
				//$cesta['typ_cesty'] = $typcesty;
			} else {
				redirect('SluzobneCesty/GetAll');	
			}
			$ids = $cesta[0]['person_id'];
			
			$ids = explode(',', $ids);
			$pids = '';
			if(in_array($personid, $ids)){
				
				foreach ($ids as $key => $pid) {
					if($pid != $personid){
						$pids .= $pid . ','; 
					}
				}
				$pids = substr($pids, 0, -1);
				$cesta[0]['person_id'] = $pids;
			}
			
			$this->SluzobneCesty_model->zmen($typcesty,$cesta[0]);
			
			$this->ukaz($typcesty, $idcesty);	
			

		}	
        
        function cities() {
            $this->load->helper('autocomplete');
            $city = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
            $cities = simple_ways_autocomplete('city', $city);
            echo json_encode($cities);
        }	
        
        function countries() {
            $this->load->helper('autocomplete');
            $country = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
            $countries = simple_ways_autocomplete('country', $country);
            echo json_encode($countries);
        }
        
        function organizations() {
            $this->load->helper('autocomplete');
            $organization = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
            $organizations = simple_ways_autocomplete('organization', $organization);
            echo json_encode($organizations);
        }
        
        private function inject_cities($table = 'odcestovani') {
            if ($table !== 'odcestovani' && $table !== 'pricestovani') { return; }
            $this->db->select('DISTINCT `city`', FALSE);
            $this->db->from($table);
            $this->db->order_by('city');
            $query = $this->db->get();
            
            $cities = array('' => '');
            if ($query->num_rows() > 0) { foreach ($query->result() as $row) {
                $cities[$row->city] = $row->city;
            }}
            
            $query->free_result();
            
            $this->load->vars(array('cities' => $cities));
        }
        
        private function inject_countries($table = 'odcestovani') {
            if ($table !== 'odcestovani' && $table !== 'pricestovani') { return; }
            $this->db->select('DISTINCT `country`', FALSE);
            $this->db->from($table);
            $this->db->order_by('country');
            $query = $this->db->get();
            
            $countries = array('' => '');
            if ($query->num_rows() > 0) { foreach ($query->result() as $row) {
                $countries[$row->country] = $row->country;
            }}
            
            $query->free_result();
            
            $this->load->vars(array('countries' => $countries));
        }
        
        private function inject_organizations($table = 'odcestovani') {
            if ($table !== 'odcestovani' && $table !== 'pricestovani') { return; }
            $this->db->select('DISTINCT `organization`', FALSE);
            $this->db->from($table);
            $this->db->order_by('organization');
            $query = $this->db->get();
            
            $organizations = array('' => '');
            if ($query->num_rows() > 0) { foreach ($query->result() as $row) {
                $organizations[$row->organization] = $row->organization;
            }}
            
            $query->free_result();
            
            $this->load->vars(array('organizations' => $organizations));
        }
        
        private function inject_persons($table = 'odcestovani') {
            if ($table !== 'odcestovani' && $table !== 'pricestovani') { return; }
            $query = $this->db->query('SELECT DISTINCT `p`.`person_id`, `p`.`name`, `p`.`surname`, `p`.`degree`, `p`.`degree2`, `p`.`degree3` FROM `people` p JOIN `' . $table . '` c ON FIND_IN_SET(`p`.`person_id`, `c`.`person_id`) ORDER BY `surname`, `name`;');
            
            $persons = array('' => '');
            if ($query->num_rows() > 0) { foreach ($query->result() as $row) {
                $build_name = array();
                if ($row->degree) { $build_name[] = $row->degree; }
                if ($row->degree2) { $build_name[] = $row->degree2; }
                $build_name[] = $row->name;
                $build_name[] = $row->surname;
                if ($row->degree3) { $build_name[] = $row->degree3; }
                $persons[$row->person_id] = implode(' ', $build_name);
            }}
            
            $query->free_result();
            
            $this->load->vars(array('persons' => $persons));
        }
        
        private function store_filter($table, $filter) {
            if ($table !== 'odcestovani' && $table !== 'pricestovani') { return; }
            $this->session->set_userdata('filter[' . $table . ']', $filter);
        }
        
        private function restore_filter($table) {
            if ($table !== 'odcestovani' && $table !== 'pricestovani') { return; }
            return $this->session->userdata('filter[' . $table . ']');
        }
		
}
	